﻿@namespace CyssBlazor.Shared.Components
@typeparam TValue
@inherits BaseValidateComponent<TValue>

@if (IsMultiple)
{
    <MultiSelect ShowSearch=ShowSearch Items="SelectedItems" @bind-Value="Value" OnSelectedItemsChanged=OnSelectedItemsChanged ShowLabel="@ShowLabel" DisplayText="@DisplayText"></MultiSelect>
}
else
{
    <Select ShowSearch=ShowSearch Items="SelectedItems" @bind-Value="Value" OnSelectedItemChanged=OnSelectedItemChanged ShowLabel="@ShowLabel" DisplayText="@DisplayText"></Select>
}

@code {

    private List<SelectedItem> SelectedItems = new List<SelectedItem>();


    [Parameter]
    public bool IsMultiple { set; get; }

    [Parameter]
    public bool ShowSearch { set; get; }
    /// <summary>
    /// 是否有空项
    /// </summary>
    [Parameter]
    public bool IsAutoAddNullItem { set; get; } = true;

    /// <summary>
    /// 空项text
    /// </summary>
    [Parameter]
    public string NullItemText { set; get; } = "请选择";

    /// <summary>
    /// 空项Value
    /// </summary>
    [Parameter]
    public string NullItemValue { set; get; } = "";

    /// <summary>
    /// SelectedItemChanged 方法
    /// </summary>
    [Parameter]
    public Func<SelectedItem, Task>? OnSelectedItemChanged { get; set; }


    /// <summary>
    /// 获得/设置 选中项集合发生改变时回调委托方法
    /// </summary>
    [Parameter]
    public Func<IEnumerable<SelectedItem>, Task>? OnSelectedItemsChanged { get; set; }

    protected override void OnInitialized()
    {
        if (typeof(TValue).IsGenericType)
        {
            IsMultiple=true;
            IsAutoAddNullItem=false;
        }
        base.OnInitialized();
    }


    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            SelectedItems=await GetSelectedItems();
            if (IsAutoAddNullItem)
            {
                SelectedItems.Insert(0, new SelectedItem { Value= NullItemValue, Text=NullItemText });
            }
            await this.InvokeAsync(StateHasChanged);
        }
    }

    /// <summary>
    /// 获取 SelectedItems
    /// </summary>
    /// <returns></returns>
    protected virtual Task<List<SelectedItem>> GetSelectedItems()
    {
        return Task.FromResult(SelectedItems);
    }
}
